import csv
import datetime
import json
import logging
import os

import requests
from sqlalchemy import and_, func, or_

from base.request import ApiBaseHandler
from common.definition import (OrderStatus, PayStatus, ret_msg)
from conf.config import BASE_DIR, DEBUG, FACTORY_UID, NFS_DIR, DOMAIN
from helper.api_helper import ApiHelper
from helper.order import get_offline_user_online_orders
from helper.payment.pay_util import generator_trade_no
from helper.user import generate_partner_qrcode

logger = logging.getLogger("wechat.handlers.reports")


class PartnerInfo(ApiBaseHandler):
    async def get(self):
        class Agency(object):
            pass

        class User(object):
            pass

        class UserAgency(object):
            pass

        session = self.get_db_session([
            {"db_table": "ebt_agency", "model": Agency},
            {"db_table": "ebt_user", "model": User},
            {"db_table": "ebt_user_agency", "model": UserAgency},
        ])

        type = int(self.get_argument("type", 2))
        agency_id = int(self.get_argument("agency_id", 0))
        page_index = int(self.get_argument("page_index", 0))
        page_size = int(self.get_argument("page_size", 10))
        ApiHelper.inspect_common_params(page_index, page_size)
        page_start = page_index * page_size
        if type == 0:
            agency_type = "初级合伙人"
            filter = dict(
                ebf_agency_type=0,
            )
        elif type == 1:
            agency_type = "高级合伙人"
            filter = dict(
                ebf_agency_type=1,
            )
        elif type == 2:
            agency_type = "事业合伙人"
            filter = dict(
                ebf_agency_type=2,
            )
        else:
            return self.write(ret_msg(data=-1, error_message="合伙人类型不存在"))

        if agency_id:
            filter["ebf_agency_id"] = agency_id
            partners = session.query(Agency).filter_by(**filter).all()
        else:
            partners = session.query(Agency).filter_by(**filter).order_by(
                Agency.ebf_agency_id.desc())[page_start: page_start + page_size]
        partner_nums = session.query(func.count(Agency.ebf_agency_id)).filter_by(**filter).scalar()
        partner_info = []
        for p in partners:
            partner = dict(
                agency_id=p.ebf_agency_id,
                name=p.ebf_agency_name,
                phone=p.ebf_agency_contact,
                parent_id=p.ebf_agency_parent_id,
                invite_uid=p.ebf_agency_invite_uid,
                career_uid=p.ebf_agency_career_uid,
                type=type,
                agency_type=agency_type
            )
            partner_info.append(partner)
        context = dict(
            partner_nums=partner_nums,
            partner_info=partner_info
        )
        return self.write(ret_msg(data=context))


class DownloadScanUer(ApiBaseHandler):
    def get_json_data(self, recommend_user, time_range, uid):
        base_url = f"https://{DOMAIN}/api/user/scan_user"
        if not time_range:
            now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            time_range = "2018-07-20 00:00:00~" + now
        if not (recommend_user or uid):
            url = base_url + "?time_range=" + time_range
        elif recommend_user:
            url = base_url + "?recommend_user=" + recommend_user + "&time_range=" + time_range
        elif uid:
            url = base_url + "?uid=" + uid + "&time_range=" + time_range
        else:
            url = base_url
        json_data = requests.get(url=url).json()
        return json_data

    def json_to_csv(self, recommend_user, time_range, uid, filename):
        json_data = []
        result = self.get_json_data(recommend_user, time_range, uid)
        scan_users = result["data"]["user_info"]
        if scan_users:
            for u in scan_users:
                json_data.append(u)
        path = os.path.join(NFS_DIR, "static/csv/")
        if not os.path.exists(path):
            os.makedirs(path)
        filepath = os.path.join(path, filename)
        if os.path.exists(filepath):
            os.remove(filepath)
            logger.info("删除scan_user.csv成功")
        f = open(filepath, 'w')
        writer = csv.writer(f)
        keys = ['序号', '微信标识', '昵称', '推荐人', '所属合伙人UID', '编号', '尾号', '关注时间']  # 表头
        writer.writerow(keys)
        i = 1
        for line in json_data:
            writer.writerow(
                [
                    str(i),
                    line['open_id'],
                    line['nickname'],
                    line['recommend_user'],
                    line['uid'],
                    line['number'],
                    line['end_num'],
                    line['create_date']
                ]
            )
            i += 1
        f.close()

    async def get(self):
        recommend_user = self.get_argument("recommend_user", None)
        time_range = self.get_argument("time_range", None)
        uid = self.get_argument("uid", None)
        logger.debug("recommend_user=%s, time_range=%s, uid=%s" % (recommend_user, time_range, uid))
        filename = "scan_user_" + generator_trade_no() + '.csv'
        self.json_to_csv(recommend_user, time_range, uid, filename)
        if DEBUG:
            base_url = "http://" + self.request.host + "/"
        else:
            base_url = "http://118.126.94.161/"
        url = base_url + "static/csv/" + filename
        logger.info("url=%s" % url)
        return self.redirect(url)


class DownloadWaitExpressOrder(ApiBaseHandler):
    async def get(self):
        class Goods(object):
            pass

        class GoodsOrder(object):
            pass

        class Carts(object):
            pass

        class UserAddress(object):
            pass

        session = self.get_db_session([
            {"db_table": "sdet_goods", "model": Goods},
            {"db_table": "sdet_cart", "model": Carts},
            {"db_table": "sdet_address", "model": UserAddress},
            {"db_table": "sdet_order", "model": GoodsOrder}
        ])
        time_range = self.get_argument("time_range", None)
        if time_range:
            start_time, end_time = ApiHelper.get_time_range(time_range)
        else:
            start_time = datetime.datetime(2018, 9, 1, 0, 0, 0)
            end_time = datetime.datetime.now()
        filters = dict(
            sdef_order_factory_uid=FACTORY_UID,
            sdef_order_pay_status=PayStatus.SUCCESS,
            sdef_order_is_delete=0
        )
        orders = session.query(
            GoodsOrder).filter_by(**filters).filter(
            or_(GoodsOrder.sdef_order_status == OrderStatus.WAIT_EXPRESS,
                GoodsOrder.sdef_order_status == OrderStatus.WAIT_PICKUP)
        ).filter(
            GoodsOrder.sdef_order_type.in_([1, 2, 4, 7, 9, 10, 11, 12, 13])).filter(
            GoodsOrder.sdef_order_create_time >= start_time).filter(
            GoodsOrder.sdef_order_create_time <= end_time).order_by(
            GoodsOrder.sdef_order_id.asc()).all()

        path = os.path.join(NFS_DIR, "static/csv/")
        if not os.path.exists(path):
            os.makedirs(path)
        filename = "wait_express_order_" + generator_trade_no() + '.csv'
        file_path = os.path.join(path, filename)
        if os.path.exists(file_path):
            os.remove(file_path)
            logger.info("删除wait_express_order.csv成功")
        f = open(file_path, 'w')
        writer = csv.writer(f)
        keys = [
            '商家订单号',
            '平台订单号',
            '收件人姓名',
            '收件人手机',
            '收件人座机',
            '收件人地址',
            '收件人公司',
            '物品内容',
            '包裹数量',
            '参考重量',
            '订单金额（元）',
            '业务类型',
            '生鲜温层',
            '付费方式',
            '是否保价',
            '保价金额（元）',
            '签单返还',
            '是否代收贷款',
            '代收货款金额（元）',
            '京尊达',
            '防撕码收集',
            '短信验证',
            '备注',
            '支付时间'
        ]
        writer.writerow(keys)
        for o in orders:
            address_id = o.sdef_order_address_id
            order_goods = json.loads(o.sdef_order_goods) if o.sdef_order_goods else []
            order_id = o.sdef_order_id
            address = session.query(UserAddress).filter_by(sdef_address_id=address_id).first()
            goods_info = ""
            for g in order_goods:
                goods_id = int(g["id"])
                goods = session.query(Goods).filter_by(sdef_goods_id=goods_id).first()
                unit = ApiHelper.get_unit(goods.sdef_goods_unit)
                goods_name = goods.sdef_goods_name
                count = str(g["count"])
                goods_info += goods_name + "(" + count + "×" + unit + ")" + ","
            goods_info = goods_info[:-1]
            if not address:
                logger.error("订单没有地址: order_id=%s" % order_id)
                raise Exception
            province = address.sdef_address_province.strip()
            city = address.sdef_address_city.strip()
            county = address.sdef_address_county.strip()
            address_detail = province + city + county + address.sdef_address_detail.strip()
            pay_time = o.sdef_order_pay_time.strftime("%Y年%m月%d日 %H:%M:%S")
            writer.writerow(
                [
                    "'" + order_id,
                    "",
                    address.sdef_address_name,
                    "'" + address.sdef_address_phone,
                    "",
                    address_detail,
                    "",
                    "红酒",
                    "",
                    1,
                    0,
                    "特惠送",
                    "普通",
                    "商家月结",
                    "否",
                    "",
                    "否",
                    "否",
                    "",
                    "",
                    "",
                    "",
                    goods_info,
                    pay_time
                ]
            )
        session.close()
        f.close()
        if DEBUG:
            base_url = "http://" + self.request.host + "/"
        else:
            base_url = "http://118.126.94.161/"
        url = base_url + "static/csv/" + filename
        logger.info("url=%s" % url)
        return self.redirect(url)


class DownloadPartnerInfo(ApiBaseHandler):
    def get_json_data(self, type, page_size, page_index):
        base_url = f"https://{DOMAIN}/api/reports/partnerinfo"
        url = base_url + "?type=" + type + "&page_size=" + page_size + "&page_index=" + page_index
        json_data = requests.get(url=url).json()
        return json_data

    def json_to_csv(self, type, page_size, page_index, filename):
        json_data = []
        while True:
            result = self.get_json_data(type, page_size, page_index)
            partners = result["data"]["partner_info"]
            if partners:
                for p in partners:
                    json_data.append(p)
                page_index = str(int(page_index) + 1)
            else:
                break
        path = os.path.join(NFS_DIR, "static/csv/")
        if not os.path.exists(path):
            os.makedirs(path)
        filepath = os.path.join(path, filename)
        if os.path.exists(filepath):
            os.remove(filepath)
            logger.info("删除scan_user.csv成功")
        f = open(filepath, 'w')
        writer = csv.writer(f)
        keys = [
            '序号',
            '合伙人编号',
            '姓名',
            '手机号码',
            '所属父级合伙人编号',
            '邀请人唯一标识',
            '所属事业合伙人唯一标识',
            '类型编号',
            '合伙人类型'
        ]
        writer.writerow(keys)
        i = 1
        for line in json_data:
            writer.writerow(
                [
                    str(i),
                    line['agency_id'],
                    line['name'],
                    line['phone'],
                    line['parent_id'],
                    line['invite_uid'],
                    line['career_uid'],
                    line['type'],
                    line['agency_type']
                ]
            )
            i += 1
        f.close()

    async def get(self):
        type = self.get_argument("type", None)
        page_index = self.get_argument("page_index", "0")
        page_size = self.get_argument("page_size", "10")
        if type:
            if int(type) == 2:
                filename = "career_partner_" + generator_trade_no() + '.csv'
            else:
                filename = "senior_partner_" + generator_trade_no() + '.csv'
        else:
            filename = "senior_partner_" + generator_trade_no() + '.csv'
        self.json_to_csv(type, page_size, page_index, filename)
        if DEBUG:
            base_url = "http://" + self.request.host + "/"
        else:
            base_url = "http://118.126.94.161/"
        url = base_url + "static/csv/" + filename
        logger.info("url=%s" % url)
        return self.redirect(url)


class DownloadQrcode(ApiBaseHandler):
    async def get(self):
        class Agency(object):
            pass

        session = self.get_db_session([
            {"db_table": "ebt_agency", "model": Agency}
        ])

        agencys = session.query(Agency).filter_by(
            ebf_agency_remarks="自动生成发卡人").filter(
            and_(Agency.ebf_agency_id >= 2640, Agency.ebf_agency_id <= 5852)).all()

        filename = "qrcode_2640_3212.csv"
        dir_path = os.path.join(BASE_DIR, "static/csv/")
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        logger.info(f"dir_path={dir_path}")
        filepath = os.path.join(dir_path, filename)
        if os.path.exists(filepath):
            os.remove(filepath)
            logger.info("删除qrcode_2640_3212.csv成功")

        f = open(filepath, 'w')
        writer = csv.writer(f)
        keys = ['二维码内容', '合伙人编号']  # 表头
        writer.writerow(keys)
        for agency in agencys:
            agency_id = agency.ebf_agency_id
            agency_uid = agency.ebf_agency_uid
            if not agency_uid:
                logger.error(f"没有agency_uid: agency_id={agency_id}")
            try:
                qr_wechat_url = generate_partner_qrcode(agency_uid)
            except Exception as e:
                logger.error(e)
                qr_wechat_url = None

            writer.writerow([qr_wechat_url, agency_id])

        f.close()
        session.close()
        return self.write(ret_msg())


class StoreUserOnlineOrders(ApiBaseHandler):
    async def get(self):
        """
        门店用户线上订单汇总报告
        """

        summary = get_offline_user_online_orders()
        ret_msg = json.dumps(summary)
        return self.write(ret_msg)
